package ext.acae2.part;

import java.beans.PropertyVetoException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.doc.DocumentVersion;
import wt.doc.WTDocument;
import wt.enterprise.RevisionControlled;
import wt.epm.EPMDocConfigSpec;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentMaster;
import wt.epm.navigator.CollectItem;
import wt.epm.navigator.EPMNavigateHelper;
import wt.epm.navigator.relationship.UIRelationships;
import wt.epm.structure.EPMDependencyLink;
import wt.epm.structure.EPMReferenceLink;
import wt.epm.structure.EPMStructureHelper;
import wt.epm.workspaces.EPMAsStoredConfig;
import wt.epm.workspaces.EPMAsStoredConfigSpec;
import wt.epm.workspaces.EPMAsStoredHelper;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectVector;
import wt.fc.PersistenceHelper;
import wt.fc.PersistentReference;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.fc.collections.WTCollection;
import wt.fc.collections.WTKeyedHashMap;
import wt.fc.collections.WTKeyedMap;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.folder.Foldered;
import wt.log4j.LogR;
import wt.part.PartDocHelper;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.pds.StatementSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.representation.Representable;
import wt.representation.Representation;
import wt.representation.RepresentationHelper;
import wt.util.WTException;
import wt.vc.VersionControlHelper;
import wt.vc.config.IteratedFolderedConfigSpec;
import ext.acae2.utilities.docpart.CSCPart;
import ext.acae2.utilities.util.CSCUtil;

public class PartHelper {
	
	private static final  Logger LOGGER =  LogR.getLogger(PartHelper.class.getName());
	
	public static List<RevisionControlled> getPartReleatedDOC(WTPart part) throws WTException, RemoteException {
		List<RevisionControlled> docList = new ArrayList<RevisionControlled>();
		List objList = CSCPart.getRelatedWTObjectByPart(part);
		for (int i = 0; i < objList.size(); i++) {
			RevisionControlled obj = (RevisionControlled) objList.get(i);
			if (obj instanceof WTDocument) {
				WTDocument doc = (WTDocument) obj;
				docList.add(doc);
				//String typeStr = TypeIdentifierUtilityHelper.service.getTypeIdentifier(doc).toString();
			}
		}
		QueryResult cadDocRs = getAssociatedCADDocuments(part);
		if (cadDocRs != null) {
			while (cadDocRs.hasMoreElements()) {
				docList.add((RevisionControlled)cadDocRs.nextElement());
			}
		}
		return docList;
	}
	
	public static QueryResult getAssociatedCADDocuments(WTPart wtpart) throws WTException {
		WTArrayList wtarraylist = new WTArrayList();
        wtarraylist.add(wtpart);
        WTKeyedMap wtkeyedmap = PartDocHelper.service.getAssociatedCADDocuments(wtarraylist);
        WTCollection wtcollection = (WTCollection)wtkeyedmap.get(wtpart);
        return getDocs(wtcollection);
	}
	
	private static QueryResult getDocs(WTCollection wtcollection)
    {
        QueryResult queryresult = new QueryResult();
        try
        {
            if(wtcollection != null)
            {
                ObjectVector objectvector = new ObjectVector();
                DocumentVersion documentversion;
                for(Iterator iterator = wtcollection.persistableIterator(); iterator.hasNext(); objectvector.addElement(documentversion))
                {
                    documentversion = (DocumentVersion)iterator.next();
                }
                queryresult.appendObjectVector(objectvector);
            }
        }
        catch(WTException wtexception)
        {
            wtexception.printStackTrace();
        }
        return queryresult;
    }
	
	
	public static void getBomConstructAssociatedCADDoc(WTPart root, WTPartConfigSpec configSpec,List<RevisionControlled> rcs) throws WTException{
		if(!rcs.contains(root)){
			rcs.add(root);
		}
		QueryResult cadDocQr = getAssociatedCADDocuments(root);
		if(cadDocQr.size()>0){
			while(cadDocQr.hasMoreElements()){
				RevisionControlled rc = (RevisionControlled) cadDocQr.nextElement();
				if(!rcs.contains(rc))
					rcs.add(rc);
			}
		}
		QueryResult childPartsQs = WTPartHelper.service.getUsesWTParts(root,configSpec);
		while (childPartsQs.hasMoreElements()) {
			Object obj[] = null;
            obj = (Object[]) childPartsQs.nextElement();
            if (obj[1] instanceof WTPart) {
                WTPart childPart = (WTPart) obj[1];
//                WTPartUsageLink alink = (WTPartUsageLink) obj[0];
                getBomConstructAssociatedCADDoc(childPart,configSpec,rcs);
            }
		}
	}
	
	//获得可视化
   	public static ArrayList getWVSApplicationData(ContentHolder holder)
   		throws WTException {
   		ArrayList arraylist = new ArrayList();
   		ContentItem contentitem = null;
        Representation representation = RepresentationHelper.service.getDefaultRepresentation((Representable)holder);
        if (representation != null) {
        	try{
            	representation = (Representation) ContentHelper.service.getContents(representation);
        	}catch(PropertyVetoException pve){
        	}
            Vector vector1 = ContentHelper.getContentList(representation);
            
            for (int l = 0; l < vector1.size(); l++) {
                contentitem = (ContentItem) vector1.elementAt(l);
                if (contentitem instanceof ApplicationData) {
                	arraylist.add((ApplicationData)contentitem);
                }
            }
        }
        return arraylist;
   	}
   	
   	/**
   	 * 
   	 * @description 查找epm关联的的part对象，epmbuildRule
   	 * @author cnie
   	 * @date 2013-6-9 下午7:12:25
   	 * @version 1.0
   	 * @param epms
   	 * @return
   	 * @throws WTException
   	 */
	public static WTKeyedHashMap getReleatedPart(WTArrayList epms)
			throws WTException {
		WTKeyedHashMap keyMap = EPMNavigateHelper
				.navigate(
						epms,
						UIRelationships.newActiveAssociatedParts(),
						new CollectItem[] { CollectItem.SEED_ID,
								CollectItem.OTHERSIDE_ID }).getResults(
						new WTKeyedHashMap(), new String[0]);
		return keyMap;
	}
	
	/**
	 * 查找二维图纸参看的三维模型 (关系是：绘图参考)
	 * epmdocument 参考关系 ReferenceBy roleB
	 * @description TODO
	 * @author cnie
	 * @date 2013-6-9 下午8:12:25
	 * @version 1.0
	 * @param epm
	 */
	public static EPMDocument getEPMReferences(EPMDocument epm) {
		
		EPMAsStoredConfig epmAsStoreConfig = (EPMAsStoredConfig) epm.getAsStoredConfigReference().getObject();
		try {
			epmAsStoreConfig = EPMAsStoredHelper.getAsStoredConfig(epm);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		EPMDocument comEpm = null;
		int builtType = 4; //绘图参考
		try {
			EPMAsStoredConfigSpec epmAsStoreConfigSpec = EPMAsStoredConfigSpec.newEPMAsStoredConfigSpec(epmAsStoreConfig);
			EPMDocConfigSpec epmDocConfigSpec = EPMDocConfigSpec.newEPMDocConfigSpec(epmAsStoreConfigSpec);
			//epmDocConfigSpec.setFoldered(itConfig);
			epmDocConfigSpec.setLatestActive();
			QuerySpec qs = new QuerySpec(EPMReferenceLink.class);

			LOGGER.debug("epm.getPersistInfo().getObjectIdentifier().getId()==="
					+ epm.getPersistInfo().getObjectIdentifier().getId());

			SearchCondition sc = new SearchCondition(EPMReferenceLink.class,
					EPMReferenceLink.ROLE_AOBJECT_REF + "."
							+ PersistentReference.KEY + "."
							+ ObjectIdentifier.ID, SearchCondition.EQUAL, epm
							.getPersistInfo().getObjectIdentifier().getId());
			qs.appendWhere(sc, new int[] { 0 });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(EPMReferenceLink.class,EPMDependencyLink.DEP_TYPE,SearchCondition.EQUAL,builtType),new int[] { 0 });
			QueryResult qr = EPMStructureHelper.service.navigateReferencesToIteration(epm, qs, true,epmDocConfigSpec);
			System.out.println(qr.size());
			if(qr.hasMoreElements()){
				comEpm = (EPMDocument) qr.nextElement();
				System.out.println(comEpm.getName()+"=========="+comEpm.getNumber()+"===="+comEpm.getVersionIdentifier().getValue()+"."+comEpm.getIterationIdentifier().getValue());
				
//				EPMDocumentMaster epmMaster = (EPMDocumentMaster) qr.nextElement();
//				QueryResult epmQr = VersionControlHelper.service.allIterationsOf(epmMaster);
//				if(epmQr.hasMoreElements())
//					comEpm = (EPMDocument) epmQr.nextElement();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return comEpm;

	}
   	
   	public static void main(String[] args) throws WTException {
//   		WTPartStandardConfigSpec standardConfigSpec = WTPartStandardConfigSpec
//				.newWTPartStandardConfigSpec(
//						ViewHelper.service.getView("Design"), null);
//		WTPartConfigSpec configSpec = WTPartConfigSpec
//				.newWTPartConfigSpec(standardConfigSpec);
//		configSpec.setStandardActive(true);
//   		WTPart part = (WTPart) CSCUtil.getObjectByOid("OR:wt.part.WTPart:253613");
//   		List<RevisionControlled> rcs = new ArrayList<RevisionControlled>();
//		getBomConstructAssociatedCADDoc(part,configSpec,rcs);
//		for(RevisionControlled rc:rcs){
//			System.out.println(rc.getName()+"====="+rc.getVersionIdentifier().getValue()+"."+rc.getIterationIdentifier().getValue());
//		}
   		
   		EPMDocument epm = (EPMDocument) CSCUtil.getObjectByOid("OR:wt.epm.EPMDocument:284999");
   		EPMDocument comEpm = getEPMReferences(epm);
//   		WTArrayList list = new WTArrayList(2);
//   		list.add(comEpm);
//   		WTKeyedHashMap keyMap = getReleatedPart(list);
//   		WTCollection wtcollection = (WTCollection)keyMap.get(comEpm);
//   		if(wtcollection!=null&&wtcollection.size()>0){
//   			System.out.println(wtcollection.size());
//   	   		WTPart part = (WTPart) wtcollection.persistableIterator().next();
//   	   		System.out.println(part.getName()+"=========="+part.getNumber()+"===="+part.getVersionIdentifier().getValue()+"."+part.getIterationIdentifier().getValue());
//   		}
   		
	}
	

}
